package flex.cc.single.api;

import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import flex.cc.PublicUtil;
import flex.cc.basicinformation.dao.ValueAddedServiceProviderDao;
import flex.cc.basicinformation.entity.ValueAddedServiceProviderEntity;
import flex.cc.common.utils.DateUtil;
import flex.cc.core.support.BaseController;
import flex.cc.drive.util.DriveDESUtil;
import flex.cc.single.service.AppointmentService;
import flex.cc.single.service.SingleDriverSynStatusService;
import flex.cc.util.APIConfigUtil;

/**
 * 单项状态同步接口
 */
@RestController
@RequestMapping(value = "/storeapi")
public class SingleDriveSynSatusController extends BaseController {

	@Resource
    private AppointmentService appointmentService;
	@Resource
    private SingleDriverSynStatusService singleDriverSynStatusService;
	@Resource
    private ValueAddedServiceProviderDao valueAddedserviceProviderDao;
    @Autowired
    private APIConfigUtil apiConfigUtil;
    

	/**
     * 单项代驾状态同步
     */
	@ResponseBody
    @RequestMapping("/singleDriverSynStatus")
    public JSONObject singleDriverSynStatus(HttpServletRequest request) throws Exception {
		JSONObject jsonResult = new JSONObject();
		long startTime = System.currentTimeMillis();
    	logger.info("DriveSynSatusController 代驾状态同步接口:begintime="+DateUtil.getStrDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
    	//状态同步业务处理
    	Boolean flag = true;
        String responseMsg = "成功";
        //读取报文
        try {
            // 设置编码
            request.setCharacterEncoding("UTF-8");
            // 读取请求报文
            String requestJson = IOUtils.toString(request.getInputStream(), "UTF-8");
            logger.info("DriveSynSatusController 代驾状态同步接口接收加密报文： "+requestJson);
            if (requestJson != null && !"".equals(requestJson)) {
            	//获取加密串
            	JSONObject requestBody = JSONObject.parseObject(requestJson);
                Map<String, String> requestBodyMap  = requestBody.toJavaObject(Map.class);
                String encryptData =  requestBodyMap.get("encryptData");
                String apiCode =  requestBodyMap.get("apiCode");//约束之后新服务商要传的唯一识别码
            	
                String provider = "";
                Map<String, Object> params = new HashMap<String, Object>();
            	if(PublicUtil.isEmpty(apiCode)){//盛大的，默认
            		params.put("apiCode", "SD");
            	}else{
            		params.put("apiCode", apiCode);
            	}
            	ValueAddedServiceProviderEntity serviceProviderEntity = valueAddedserviceProviderDao.getOneByParams(params);
        		if(PublicUtil.isNotEmpty(serviceProviderEntity)){
        			provider = String.valueOf(serviceProviderEntity.getId());
        		}else{
        			flag = false;
                    responseMsg = "apiCode信息未配置，请联系业务人员";
                	logger.error("DriveSynSatusController 代驾状态同步接口失败:apiCode信息未配置，请联系业务人员");
        		}
                
                String key = apiConfigUtil.getApiConfig(provider, "drive_decode");
                String key3Des = apiConfigUtil.getApiConfig(provider, "store_key3Des");
                
            	String synSatusRequestJson = DriveDESUtil.driverDecrypt(encryptData,key,key3Des);
            	logger.info("DriveSynSatusController 代驾状态同步接口接收解密报文： "+synSatusRequestJson);
                // 调用业务处理 =============================
            	logger.info("storeapi/synSatus requestJson:" + synSatusRequestJson);
                JSONObject synSatusRequestBody = JSONObject.parseObject(synSatusRequestJson);
                Map<String, Object> synSatusRequestBodyMap = synSatusRequestBody.toJavaObject(Map.class);
                flag = true;
                jsonResult = singleDriverSynStatusService.driverSynStatus(synSatusRequestBodyMap,requestJson); 
                logger.info("storeapi/synSatus： "+jsonResult);
            } else {
                flag = false;
                responseMsg = "接口处理异常:请求报文为空";
                logger.error("storeapi/synSatus 接口处理异常:请求报文为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
            responseMsg = "数据接收异常";
            logger.error("storeapi/synSatus 数据接收异常:" + e.getMessage());
        }
        if(!flag){
        	// 生成响应报文
            jsonResult.put("responseCode", "ERROR");
        	jsonResult.put("responseMsg", responseMsg);
        }
    	long endTime = System.currentTimeMillis();
    	logger.info("DriveSynSatusController 代驾状态同步接口:endtime="+DateUtil.getStrDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS")+"; 处理时长="+(endTime - startTime)+"; resJson=?"+jsonResult.toString());
		return jsonResult;
	}
	
    /**
     * 单项代驾预约新增测试接口
     */
	@ResponseBody
    @RequestMapping("/createDriverAppointment")
    public JSONObject createDriverAppointment(HttpServletRequest request) throws Exception {
		JSONObject jsonResult = new JSONObject();
        // 进入接口时间
        long startTime = System.currentTimeMillis();
        logger.info("storeapi/createDriverAppointment 进入接口:time=" + DateUtil.getStrDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));

        Boolean flag = true;
        String responseMsg = "成功";
        //读取报文
        try {
            // 设置编码
            request.setCharacterEncoding("UTF-8");
            // 读取请求报文
            String requestJson = IOUtils.toString(request.getInputStream(), "UTF-8");
            requestJson = URLDecoder.decode(requestJson, "UTF-8");
            if (requestJson != null && !"".equals(requestJson)) {
                // 调用业务处理 =============================
            	logger.info("storeapi/createDriverAppointment requestJson:" + requestJson);
                JSONObject requestBody = JSONObject.parseObject(requestJson);
                Map<String, Object> requestBodyMap = requestBody.toJavaObject(Map.class);
                //请求下游
                flag = true;
                jsonResult = appointmentService.createDriverAppointment(requestBodyMap); 
                logger.info("storeapi/createDriverAppointment： "+jsonResult);
            } else {
                flag = false;
                responseMsg = "接口处理异常:请求报文为空";
                logger.error("storeapi/createDriverAppointment 接口处理异常:请求报文为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
            responseMsg = "数据接收异常";
            logger.error("storeapi/createDriverAppointment 数据接收异常:" + e.getMessage());
        }
        if(!flag){
        	// 生成响应报文
            jsonResult.put("responseCode", "01");
        	jsonResult.put("responseMsg", responseMsg);
        }
        logger.info("storeapi/createDriverAppointment responseJson:" + jsonResult);
        // 离开接口时间
        long endTime = System.currentTimeMillis();
        logger.info("storeapi/createDriverAppointment 离开接口:time=" + DateUtil.getStrDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS") + ";处理时长:" + (endTime - startTime));

        return jsonResult;
    }
	
	
	/**
     * 单项到店预约新增测试接口
     */
	@ResponseBody
    @RequestMapping("/createStoreAppointment")
    public JSONObject createStoreAppointment(HttpServletRequest request) throws Exception {
		JSONObject jsonResult = new JSONObject();
        // 进入接口时间
        long startTime = System.currentTimeMillis();
        logger.info("storeapi/createStoreAppointment 进入接口:time=" + DateUtil.getStrDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));

        Boolean flag = true;
        String responseMsg = "成功";
        //读取报文
        try {
            // 设置编码
            request.setCharacterEncoding("UTF-8");
            // 读取请求报文
            String requestJson = IOUtils.toString(request.getInputStream(), "UTF-8");
            requestJson = URLDecoder.decode(requestJson, "UTF-8");
            if (requestJson != null && !"".equals(requestJson)) {
                // 调用业务处理 =============================
            	logger.info("storeapi/createStoreAppointment requestJson:" + requestJson);
                JSONObject requestBody = JSONObject.parseObject(requestJson);
                Map<String, Object> requestBodyMap = requestBody.toJavaObject(Map.class);
                //请求下游
                flag = true;
                jsonResult = appointmentService.createStoreAppointment(requestBodyMap); 
                logger.info("storeapi/createStoreAppointment： "+jsonResult);
            } else {
                flag = false;
                responseMsg = "接口处理异常:请求报文为空";
                logger.error("storeapi/createStoreAppointment 接口处理异常:请求报文为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
            responseMsg = "数据接收异常";
            logger.error("storeapi/createStoreAppointment 数据接收异常:" + e.getMessage());
        }
        if(!flag){
        	// 生成响应报文
            jsonResult.put("responseCode", "01");
        	jsonResult.put("responseMsg", responseMsg);
        }
        logger.info("storeapi/createStoreAppointment responseJson:" + jsonResult);
        // 离开接口时间
        long endTime = System.currentTimeMillis();
        logger.info("storeapi/createStoreAppointment 离开接口:time=" + DateUtil.getStrDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS") + ";处理时长:" + (endTime - startTime));

        return jsonResult;
    }
}
